﻿package com.bieyang.anjia.ui.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.TreeSet;

import org.json.JSONException;
import org.json.JSONObject;
import org.opencv.LoadObj.CameraCtrlView;
import org.opencv.LoadObj.LoadObjDetector;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.webrtc.mqttclientsample.ISocketClient;
import com.bieyang.anjia.R;
import com.bieyang.anjia.module.Device;
import com.bieyang.anjia.module.FileModel;
import com.bieyang.anjia.module.SubStates;
import com.bieyang.anjia.module.SubStates.DayModeStates;
import com.bieyang.anjia.module.SubStates.NightModeStates;
import com.bieyang.anjia.net.FileLoadManager;
import com.bieyang.anjia.net.FileLoadManager.UploadCallback;
import com.bieyang.anjia.ui.activity.SubMain;
import com.bieyang.anjia.utils.ApplicationUtils;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.SubUtils;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.Configuration;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * 忠机
 * */
@SuppressLint("SimpleDateFormat")
public class SubMain extends BaseActivity implements CvCameraViewListener2,
		OnClickListener, SensorEventListener {
	long resumeMillis;
	public static String voiceUrl;
	// 报警类型(七牛信息上传使用)
	public static String AlarmType = "";
	Animation animOn, animOff;
	// 上一次报警触发时间
	boolean full = false;
	private long lastTime, loginTime;
	// 传感器监上一次触发时间
	private static Activity instance;
	SubUtils subUtils = new SubUtils();
	// private RecordVideoUtils recordVideo;
	// private boolean activityIsActive = true;
	// 报警处理
	// private boolean isAlarming = false;
	private boolean nightMotionOn;
	@SuppressLint("HandlerLeak")
	final Handler uiHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				alarm(msg);
				break;
			case 1:
				setFlashStates();
				break;
			case 2:
				FileModel model = (FileModel) msg.obj;
				Log.i("qiniu", model.filePath + model.key + model.token + "");
				App.netManager.getToken(uiHandler, model, instance);
				break;
			case Constants.GET_TOKEN_SUCEESS:
				FileModel upLoadmodel = (FileModel) msg.obj;
				FileLoadManager.uploadByPath(upLoadmodel, new UploadCallback() {

					@Override
					public void callback(int fileSize, String key,
							String fileType) {
						subUtils.upLoadFilePath(fileSize, key, fileType,
								instance);
						subUtils.clearFile(instance);
					}
				});
				break;
			case Constants.GET_TOKEN_FAILED:
				Show.toast(instance, R.string.internet_exception);
				break;
			case Constants.QUERY_SUB_SET_SUCCESS:
				Device device = (Device) msg.obj;
				if (null != device) {
					subUtils.saveSubSet(device, instance);
					getSubStates();
				} else {
					Show.toast(instance, R.string.please_set);
				}
				break;
			case Constants.QUERY_SUB_SET_FAILED:
				Show.toast(instance, R.string.internet_exception);
				break;
			case 11:
				if (SharedPrefsUtil.getBooleanValue(instance, "subIsLogin",
						false)) {
					getSubStates();
				}
				break;
			case 12:
				if (SharedPrefsUtil.getBooleanValue(instance, "subIsLogin",
						false)) {
					setName(deviceName);
				}
				break;
			case 13:
				if (SharedPrefsUtil.getBooleanValue(instance, "subIsLogin",
						false)) {
					subExit();
				}
				break;
			case Constants.LOGOUT_SUCESS:
				sysExit();
				break;
			case Constants.LOGOUT_FAIL:
				Show.toast(instance,
						instance.getString(R.string.internet_exception));
				break;
			case Constants.GET_ALARM_MUSIC_URL_SUCCESS:
				try {
					if (null != msg.obj) {
						voiceUrl = ((JSONObject) msg.obj).getString("url");
					}
					System.out.println(voiceUrl + "");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			default:
				break;
			}

		}
	};

	/**
	 * 报警设置
	 * */
	private SubStates subStates;
	// 人体识别相关
	private Mat mRGBA;
	private Mat mGray;
	private LoadObjDetector mNativeDetector;
	private CameraCtrlView mCameraView;
	/** 录制视频类 */
	private MediaPlayer player = new MediaPlayer();
	/** 威慑语音 */
	private HashMap<String, Integer> voiceKeyAndId;
	// 上一次按下back键时间
	private long exitMillis;
	// 忠机广播
	private SubReceiver subReceiver = new SubReceiver();
	private PendingIntent flashPendingIntent;
	private AlarmManager alarmManager;

	// 获取设备信息
	private TextView deviceName, userPhone, diviceUid;
	// 关屏
	private Button subScreenOff;
	private ImageView subBack, imgBj, userIcon;
	// 生成二维码按钮
	// private Button createQrcode;
	// 二维码显示控件
	// private ImageView qrCodeBitmapShow;
	// 二维码位图
	// private Bitmap qrCodeBitmap;
	// 二维码显示dialog
	// private AlertDialog qrCodeDialog;
	// 二维码尺寸
	// private int size = 500;

	@SuppressWarnings("unused")
	private ISocketClient mClient;
	private String uuid;
	SensorManager mSensorManager;
	long mLastUpdate;
	TextView mXAccelView, mYAccelView, mZAccelView;
	private Sensor mAccelerometer;
	private static final Scalar OBJ_RECT_COLOR = new Scalar(0, 255, 0, 255);
	private static final String TAG = "Opencv:LoadObj";
	private boolean mDetectFlag = false;
	private final float mAlpha = 0.8f;
	private float[] mGravity = new float[3];
	private float[] mAccel = new float[3];
	Window window;
	WindowManager.LayoutParams lp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		instance = this;
		uuid = SubUtils.getUuid(this);
		window = getWindow();
		lp = window.getAttributes();
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.sub_main_activity);

		if (SharedPrefsUtil.getBooleanValue(instance, "subIsLogin", false)
				&& Configuration.ORIENTATION_LANDSCAPE == getResources()
						.getConfiguration().orientation) {
			downLoadStates(instance);
			int a = SharedPrefsUtil.getIntValue(instance, "subLogin", 0);
			if (a < 5) {
				Show.toast(instance, R.string.first_comein_zhongji,
						Toast.LENGTH_LONG);
				SharedPrefsUtil.putValue(instance, "subLogin", ++a);
			}
		}
		initAnim();
		full(full);
		setSubBroadCast();
		initVoiceMap();
		initView();
		initSensor();
	}

	/**
	 * 下载采集端配置
	 * 
	 * @param instance
	 *            上下文
	 */
	private void downLoadStates(final Context instance) {
		if (SharedPrefsUtil.getBooleanValue(instance, "subIsLogin", false)) {
			if (Configuration.ORIENTATION_LANDSCAPE == getResources()
					.getConfiguration().orientation) {
				Device device = new Device();
				device.setUuid(SubUtils.getUuid(instance));
				device.setMemberId(SharedPrefsUtil.getStringValue(instance,
						"memberId", "0"));
				App.netManager.queryCollectionTerminal(device, uiHandler);
			}
		} else {
			Show.toast(instance, instance.getString(R.string.please_login));
		}
	}

	/**
	 * 初始化传感器
	 */
	private void initSensor() {
		// Get reference to SensorManager
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		// Get reference to Accelerometer
		if (null == (mAccelerometer = mSensorManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER))) {
			// Log.i(TAG, "Sensor Service failed!");
			finish();
		}
		mLastUpdate = System.currentTimeMillis();
	}

	/**
	 * 初始化开关屏动画
	 */
	private void initAnim() {
		animOn = AnimationUtils.loadAnimation(instance, R.anim.img_alpha_on);
		animOn.setFillAfter(true);
		animOff = AnimationUtils.loadAnimation(instance, R.anim.img_alpha_off);
		animOff.setFillAfter(true);
	}

	/**
	 * 注册闪光灯设置计时器
	 */
	private void setSubBroadCast() {
		alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		Intent flashIntent = new Intent();
		flashIntent.setAction(Constants.CAMERA_FLASH_MODE);
		flashPendingIntent = PendingIntent.getBroadcast(instance, 1,
				flashIntent, 1);
		alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
				System.currentTimeMillis() + Constants.FLASH_INTERVAL_MILLIS,
				Constants.FLASH_INTERVAL_MILLIS, flashPendingIntent);
	}

	/**
	 * 初始化威慑语音集
	 */
	private void initVoiceMap() {
		AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		am.setStreamVolume(AudioManager.STREAM_MUSIC,
				am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
		voiceKeyAndId = subUtils.getVoiceMap(SubMain.this);
	}

	/**
	 * 开屏操作
	 */
	private void screenOn() {
		imgBj.setEnabled(false);
		imgBj.startAnimation(animOff);
		full(full);
		uiHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				imgBj.clearAnimation();
				imgBj.setVisibility(View.GONE);
				lp.screenBrightness = 0.5f;
				lp.buttonBrightness = 0.5f;
				try {
					window.setAttributes(lp);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 1000);
	}

	/** 初始化控件 */
	void initView() {
		imgBj = (ImageView) findViewById(R.id.imgBj);
		imgBj.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				App.screenStates = false;
				screenOn();
			}
		});
		userPhone = (TextView) findViewById(R.id.user_phone);
		userIcon = (ImageView) findViewById(R.id.user_icon);
		userIcon.setOnClickListener(this);
		userPhone.setOnClickListener(this);
		String phone = SharedPrefsUtil.getStringValue(instance, "phone", "");
		if (11 == phone.length()) {
			userPhone.setText(phone.substring(0, 3) + "****"
					+ phone.substring(phone.length() - 4));
		} else {
			userPhone.setText(phone);
		}
		deviceName = (TextView) findViewById(R.id.sub_divice_name);
		setName(deviceName);
		diviceUid = (TextView) findViewById(R.id.sub_divice_uid);
		diviceUid.setText(uuid);
		// setUid(diviceUid);
		subBack = (ImageView) findViewById(R.id.sub_back);
		subScreenOff = (Button) findViewById(R.id.sub_screen_off);
		subScreenOff.setOnClickListener(this);
		// createQrcode = (Button) findViewById(R.id.create_qrcode);
		// if (App.subIsLogin) {
		// createQrcode.setVisibility(View.GONE);
		// } else {
		// createQrcode.setVisibility(View.VISIBLE);
		// }
		subBack.setOnClickListener(this);
		// createQrcode.setOnClickListener(this);
		// qrCodeBitmapShow = new ImageView(instance);
		// qrCodeBitmapShow.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// qrCodeDialog.dismiss();
		// }
		// });
		// qrCodeDialog = new AlertDialog.Builder(instance).setView(
		// qrCodeBitmapShow).create();
		mCameraView = (CameraCtrlView) findViewById(R.id.sub_main_surface_view);
		mCameraView.setVisibility(View.VISIBLE);
		mCameraView.setVisibility(SurfaceView.VISIBLE);
		mCameraView.setCvCameraViewListener(this);
		mXAccelView = (TextView) findViewById(R.id.xx_highpass_view);
		mYAccelView = (TextView) findViewById(R.id.yy_highpass_view);
		mZAccelView = (TextView) findViewById(R.id.zz_highpass_view);

	}

	// /**
	// * 显示设备uid
	// *
	// * @param textview
	// */
	// void setUid(TextView textview) {
	// uuid = SubUtils.getUuid(this);
	// int count = uuid.length() / 4;
	// StringBuffer sb = new StringBuffer("");
	// for (int i = 0; i < count; i++) {
	// sb.append(uuid.substring(i * 4, (i + 1) * 4) + " ");
	// }
	// sb.append(uuid.substring(count * 4));
	// diviceUid.setText(sb.toString());
	// }

	/**
	 * 设置设备名称
	 * 
	 * @param textview
	 *            显示名称控件
	 */
	private void setName(TextView textview) {
		textview.setText(SharedPrefsUtil.getStringValue(instance, "deviceName",
				uuid.substring(uuid.length() > 10 ? uuid.length() - 10 : 0)));
	}

	/**
	 * 判断当前为白天还是夜间
	 * 
	 * @return 0-白天 1-夜间 2-不在报警时间段内
	 * */
	private int getDayOrNight() {
		Calendar calendar = Calendar.getInstance();

		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
		long currentMillis = calendar.getTimeInMillis();
		if (null == subStates) {
			return 2;
		}

		DayModeStates dayModeStates = subStates.getDayModeStates();
		NightModeStates nightModeStates = subStates.getNightModeStates();
		if (null == dayModeStates || null == nightModeStates) {
			return 2;
		}
		calendar.set(Calendar.HOUR_OF_DAY, dayModeStates.getStartHour());
		calendar.set(Calendar.MINUTE, dayModeStates.getStartMinute());
		long dayStartMillis = calendar.getTimeInMillis();
		calendar.set(Calendar.HOUR_OF_DAY, dayModeStates.getStopHour());
		calendar.set(Calendar.MINUTE, dayModeStates.getStopMinute());
		long dayStopMillis = calendar.getTimeInMillis();
		calendar.set(Calendar.HOUR_OF_DAY, nightModeStates.getStartHour());
		calendar.set(Calendar.MINUTE, nightModeStates.getStartMinute());
		long nightStartMillis = calendar.getTimeInMillis();
		// if (SubSetActivity.NIGHT_START_TIME >= SubSetActivity.DAY_STOP_TIME
		// && nightModeStates.getStopHour() >= SubSetActivity.NIGHT_START_TIME
		// && nightModeStates.getStopMinute() <= SubSetActivity.NIGHT_STOP_TIME)
		// {
		// calendar.add(Calendar.DATE, 1);
		// }
		calendar.set(Calendar.HOUR_OF_DAY, nightModeStates.getStopHour());
		calendar.set(Calendar.MINUTE, nightModeStates.getStopMinute());
		long nightStopMillis = calendar.getTimeInMillis();
		if (currentMillis > dayStartMillis && currentMillis < dayStopMillis) {
			if (null == subStates.getWeekSet()
					|| !subStates.getWeekSet().contains(dayOfWeek)) {
				return 2;
			}
			return 0;
		} else if (currentMillis > nightStartMillis
				&& currentMillis < nightStopMillis) {
			if (null == subStates.getWeekSet()
					|| !subStates.getWeekSet().contains(dayOfWeek)) {
				return 2;
			}
			return 1;
		} else {
			return 2;
		}
	}

	/**
	 * 报警:播放威慑语音
	 * 
	 * @param modeCode
	 *            模式码 0-白天 1-夜间 其他-不在设置时间内
	 * */
	private void subAlarmPlayVoice(int modeCode) {
		String alarmVoice;
		switch (modeCode) {
		case 0:
			alarmVoice = SharedPrefsUtil.getStringValue(instance,
					Constants.AlARM_PLAY_VOICE,
					getString((R.string.sub_states_null)));
			break;
		case 1:
			alarmVoice = SharedPrefsUtil.getStringValue(instance,
					Constants.AlARM_PLAY_VOICE,
					getString((R.string.sub_states_null)));
			break;
		default:
			return;
		}

		if (null != player && player.isPlaying()) {
			player.stop();
			player.reset();
		}
		player.reset();
		if (!alarmVoice.equals(getString((R.string.sub_states_null)))) {
			try {
				if (null == voiceKeyAndId.get(alarmVoice)) {
					if (null == voiceUrl) {
						return;
					} else {
						player.setDataSource(voiceUrl);
					}
				} else {
					AssetFileDescriptor afd = instance.getResources()
							.openRawResourceFd(
									(Integer) voiceKeyAndId.get(alarmVoice));
					player.setDataSource(afd.getFileDescriptor(),
							afd.getStartOffset(), afd.getLength());
					afd.close();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				player.setOnPreparedListener(new OnPreparedListener() {

					@Override
					public void onPrepared(MediaPlayer mp) {
						// TODO Auto-generated method stub
						player.start();
					}
				});
				player.prepareAsync();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			if (null != player && player.isPlaying()) {
				player.stop();
				player.reset();
			}
		}
	}

	/**
	 * 报警:拍照或录像
	 * 
	 * @param modeCode
	 *            模式码 0-白天 1-夜间 其他-不在设置时间内
	 * */
	private void subAlarmPhotoAndVideo(int modeCode) {
		String methods = null;
		switch (modeCode) {
		case 0:
			methods = subStates.getAlarmMethods();
			break;
		case 1:
			methods = subStates.getAlarmMethods();
			break;
		default:
			return;
		}
		if (methods.equals(getString(R.string.sub_take_three))) {
			takeThree();
		} else if (methods.equals(getString(R.string.sub_take_one))) {
			takeOne();
		} else if (methods.equals(getString(R.string.sub_take_video))) {
			recordVideo(modeCode);
		}

	}

	/**
	 * 拍照
	 * 
	 * @param folderPath
	 *            文件夹名
	 * @param fileName
	 *            文件名
	 */
	private void takePicture(String folderPath, String fileName) {
		String filePath = folderPath + fileName;
		mCameraView.takePicture(filePath);
	}

	/**
	 * 获取配置信息
	 * */
	void getSubStates() {

		String dayStart = SharedPrefsUtil.getStringValue(instance,
				Constants.DAY_MODE_START_TIME,
				getString(R.string.sub_mode_start_time));
		String dayStop = SharedPrefsUtil.getStringValue(instance,
				Constants.DAY_MODE_STOP_TIME,
				getString(R.string.sub_mode_stop_time));
		String mesures = SharedPrefsUtil.getStringValue(instance,
				Constants.ALARM_MEASURES, getString(R.string.sub_body_recg));
		String alarm = SharedPrefsUtil.getStringValue(instance,
				Constants.AlARM_METHODS, getString((R.string.sub_take_video)));
		String voice = SharedPrefsUtil.getStringValue(instance,
				Constants.AlARM_PLAY_VOICE,
				getString((R.string.sub_states_null)));
		String nightStart = SharedPrefsUtil.getStringValue(instance,
				Constants.NIGHT_MODE_START_TIME,
				getString(R.string.sub_night_start_time));
		String nightStop = SharedPrefsUtil.getStringValue(instance,
				Constants.NIGHT_MODE_STOP_TIME,
				getString(R.string.sub_night_stop_time));
		boolean flashLight = SharedPrefsUtil.getBooleanValue(instance,
				Constants.FLASH_LIGHT, true);
		TreeSet<Integer> chooseSet = subUtils.getWeekDaySet(instance,
				SharedPrefsUtil.getSetValue(SubMain.this, Constants.WEEK_DAY,
						subUtils.initWeekSet(instance)));
		if (subStates == null) {
			subStates = new SubStates();
		}
		DayModeStates dayMode = subStates.getDayModeStates();
		if (null == dayMode) {
			dayMode = new DayModeStates();
			subStates.setDayModeStates(dayMode);
		}
		NightModeStates nightMode = subStates.getNightModeStates();
		if (null == nightMode) {
			nightMode = new NightModeStates();
			subStates.setNightModeStates(nightMode);
		}
		subStates.setWeekSet(chooseSet);
		subStates.setAlarmMeasure(mesures);
		dayMode.setStartHour(Integer.parseInt(dayStart.substring(0, 2)));
		dayMode.setStartMinute(Integer.parseInt(dayStart.substring(
				dayStart.length() - 2, dayStart.length())));
		dayMode.setStopHour(Integer.parseInt(dayStop.substring(0, 2)));
		dayMode.setStopMinute(Integer.parseInt(dayStop.substring(
				dayStop.length() - 2, dayStop.length())));

		subStates.setAlarmVoice(voice);
		subStates.setAlarmMethods(alarm);
		nightMode.setStartHour(Integer.parseInt(nightStart.substring(0, 2)));
		nightMode.setStartMinute(Integer.parseInt(nightStart.substring(
				nightStart.length() - 2, nightStart.length())));
		nightMode.setStopHour(Integer.parseInt(nightStop.substring(0, 2)));
		nightMode.setStopMinute(Integer.parseInt(nightStop.substring(
				nightStop.length() - 2, nightStop.length())));
		nightMode.setFlashLight(flashLight);
		System.out.println(subStates.getAlarmMeasure() + "\n"
				+ subStates.getAlarmMethods() + "\n"
				+ subStates.getAlarmVoice() + "\n"
				+ subStates.getWeekSet().size() + "天" + "\n"
				+ subStates.getDayModeStates().getStartHour() + ":"
				+ subStates.getDayModeStates().getStartMinute() + "-"
				+ subStates.getDayModeStates().getStopHour() + ":"
				+ subStates.getDayModeStates().getStopMinute() + "\n"
				+ subStates.getNightModeStates().getStartHour() + ":"
				+ subStates.getNightModeStates().getStartMinute() + "-"
				+ subStates.getNightModeStates().getStopHour() + ":"
				+ subStates.getNightModeStates().getStopMinute() + "\n"
				+ subStates.getNightModeStates().isFlashLight());
		if (null == voiceKeyAndId.get(voice)) {
			App.netManager.getAlarmMusicUrl(voice, uiHandler);
		}
	}

	@Override
	protected void onResume() {
		// activityIsActive = true;
		super.onResume();
		getSubStates();
		// 注册变化监听
		startAlarm();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constants.UPDATE_NAME);
		filter.addAction(Constants.CAMERA_FLASH_MODE);
		filter.addAction(Constants.UPDATE_SETTING);
		filter.addAction(Constants.DELETE_SUB);
		filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		registerReceiver(subReceiver, filter);
	}

	@Override
	protected void onPause() {
		mSensorManager.unregisterListener(this);
		stopAlarm();
		if (nightMotionOn) {
			nightMotionOn = !nightMotionOn;
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		subOff();
	}

	/**
	 * 退出界面操作
	 */
	private void subOff() {
		if (null != player) {
			if (player.isPlaying()) {
				try {
					player.stop();
				} catch (IllegalStateException e) {

				}
			}
			player.reset();
			player.release();
			player = null;
		}
		alarmManager.cancel(flashPendingIntent);
		mCameraView.disableView();
		mNativeDetector.release();
	}

	@Override
	public void onCameraViewStarted(int width, int height) {
		mGray = new Mat();
		mRGBA = new Mat();
		mNativeDetector.InitObj(width, height);
		mDetectFlag = true;
	}

	@Override
	public void onCameraViewStopped() {
		mGray.release();
		mRGBA.release();
	}

	@SuppressWarnings("unused")
	@Override
	public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
		mRGBA = inputFrame.rgba();
		// mGray = inputFrame.gray();
		MatOfRect objMat = new MatOfRect();
		MatOfRect borderMat = new MatOfRect();
		switch (getDayOrNight()) {
		case 0:
			if (subStates.getAlarmMeasure().equals(
					getString(R.string.sub_body_recg))) {
				bodyRec(objMat);
			} else {
				motionD();
			}
			break;
		case 1:
			if (nightMotionOn) {
				if (subStates.getAlarmMeasure().equals(
						getString(R.string.sub_body_recg))) {
					bodyRec(objMat);
				} else {
					motionD();
				}
			}
			break;
		default:
			break;
		}
		// mNativeDetector.BorderAlarm(mRGBA, borderMat);
		if (objMat.empty()) {
			return mRGBA;
		}
		return mRGBA;
	}

	/**
	 * 人体识别
	 * */
	private void bodyRec(MatOfRect objMat) {
		mNativeDetector.detect(mRGBA, objMat);
		int info = mNativeDetector.getObjInfo(objMat);
		if (0 < info) {
			System.out.println(info + "人体识别");
			Rect[] objArray = objMat.toArray();
			System.out.println();
			for (int i = 0; i < objArray.length; i++) {
				Core.rectangle(mRGBA, objArray[i].tl(), objArray[i].br(),
						OBJ_RECT_COLOR, 3);
			}
			Message msg = Message.obtain();
			msg.what = 0;
			msg.obj = getString(R.string.sub_body_recg);
			uiHandler.sendMessage(msg);
		}

	}

	/**
	 * 动目检测
	 * */
	private void motionD() {
		if (mNativeDetector.motionDetect(mRGBA)) {
			System.out.println("动目检测");
			Core.putText(mRGBA, "WARNING:Motion Target!", new Point(200, 30),
					0, 1.0, new Scalar(200, 0, 200, 255));
			Message msg = Message.obtain();
			msg.what = 0;
			msg.obj = getString(R.string.sub_dys);
			uiHandler.sendMessage(msg);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Constants.RESULT_CODE) {
			if (requestCode == Constants.REQUEST_CODE) {
				getSubStates();
			}
		}
		if (resultCode == Constants.RECORD_VIDEO_CODE) {
			String path = data.getStringExtra(Constants.VIDEO_PATH);
			Log.i("qiniu", path);
			FileModel model = new FileModel();
			model.filePath = path;
			Message msg = Message.obtain();
			msg.what = 2;
			msg.obj = model;
			uiHandler.sendMessage(msg);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (View.VISIBLE == imgBj.getVisibility()) {
			screenOn();
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long exitMillis = System.currentTimeMillis();
			if (exitMillis - this.exitMillis < 5000) {
				subExit();

			} else {
				Show.toast(instance, getString(R.string.sub_press_again));
			}
			this.exitMillis = exitMillis;
		}
		return false;
	}

	/**
	 * 广播接收器 包含意图:设置闪光灯,更新采集端设置,更新名称,删除忠机
	 * 
	 * @author M.y.q
	 * 
	 */
	public class SubReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) {
				Log.d("home", "home(sub)");
				subExit();
			} else if (intent.getAction().equals(Constants.CAMERA_FLASH_MODE)) {
				uiHandler.sendEmptyMessage(1);
			} else if (intent.getAction().equals(Constants.UPDATE_SETTING)) {
				uiHandler.sendEmptyMessage(11);
			} else if (intent.getAction().equals(Constants.UPDATE_NAME)) {
				uiHandler.sendEmptyMessage(12);
			} else if (intent.getAction().equals(Constants.DELETE_SUB)) {
				uiHandler.sendEmptyMessage(13);
			}
		}

	}

	/**
	 * 开启预警
	 */
	private void startAlarm() {

		if (OpenCVLoader.initDebug()) {
			// mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
			Log.i(TAG, "OPENCV Static Initialization");
			System.loadLibrary("opencv_java");

		} else {
			Log.i(TAG, "Static Initialization failed");
		}

		System.loadLibrary("LoadObjDetector");
		mCameraView.setResolution();
		mNativeDetector = new LoadObjDetector();
		mCameraView.enableView();
		// mCameraView.setResolution();
		resumeMillis = System.currentTimeMillis();
		mSensorManager.registerListener(this, mAccelerometer,
				SensorManager.SENSOR_DELAY_UI);

		if (0 == lastTime) {
			lastTime = System.currentTimeMillis();
		}
	}

	/**
	 * 停止预警
	 */
	private void stopAlarm() {
		if (mCameraView != null)
			mCameraView.disableView();
		unregisterReceiver(subReceiver);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.sub_back:
			subExit();
			// AlarmType = getString(R.string.sub_body_recg);
			// takeOne();
			break;
		case R.id.sub_screen_off:
			lp.screenBrightness = 0.01f;
			lp.buttonBrightness = 0.01f;
			try {
				window.setAttributes(lp);
			} catch (Exception e) {
				e.printStackTrace();
			}
			App.screenStates = true;
			imgBj.setVisibility(View.VISIBLE);
			imgBj.setEnabled(true);
			imgBj.startAnimation(animOn);
			full(full);
			break;
		// case R.id.create_qrcode:
		// if (null == qrCodeBitmap) {
		// qrCodeBitmap = subUtils.createQRImage(uuid, size);
		// }
		// qrCodeBitmapShow.setImageBitmap(qrCodeBitmap);
		// qrCodeDialog.show();
		// break;
		case R.id.user_phone:
			startActivity(new Intent(instance, AcMyInfo.class));
			break;
		case R.id.user_icon:
			startActivity(new Intent(instance, AcMyInfo.class));
			break;
		default:
			break;
		}
	}

	/***
	 * 状态栏隐藏于显示切换
	 * 
	 * @param enable
	 *            当前状态 true-非全屏 false全屏
	 */
	private void full(boolean enable) {

		if (enable) {

			WindowManager.LayoutParams lp = getWindow().getAttributes();

			lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;

			getWindow().setAttributes(lp);

			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
		} else {

			WindowManager.LayoutParams attr = getWindow().getAttributes();

			attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);

			getWindow().setAttributes(attr);

			getWindow().clearFlags(
					WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
		}
		full = !full;

	}

	@Override
	public void onSensorChanged(SensorEvent event) {

		if (mDetectFlag == false)
			return;
		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

			long actualTime = System.currentTimeMillis();
			if (actualTime - mLastUpdate > 100) {

				if (actualTime - resumeMillis > 3000) {

					mLastUpdate = actualTime;

					float rawX = event.values[0];
					float rawY = event.values[1];
					float rawZ = event.values[2];

					// Apply low-pass filter
					mGravity[0] = lowPass(rawX, mGravity[0]);
					mGravity[1] = lowPass(rawY, mGravity[1]);
					mGravity[2] = lowPass(rawZ, mGravity[2]);

					// Apply high-pass filter
					mAccel[0] = highPass(rawX, mGravity[0]);
					mAccel[1] = highPass(rawY, mGravity[1]);
					mAccel[2] = highPass(rawZ, mGravity[2]);
					// mXValueView.setText(String.valueOf(rawX));
					// mYValueView.setText(String.valueOf(rawY));
					// mZValueView.setText(String.valueOf(rawZ));
					if (mAccel[0] + mAccel[1] > 1) {
						Message msg = Message.obtain();
						msg.what = 0;
						msg.obj = getString(R.string.sub_moved);
						uiHandler.sendMessage(msg);

						if (mNativeDetector.IsSensorEnable()) {
							mNativeDetector.BGResetShake();
							mXAccelView.setText(String.valueOf(mAccel[0]));
							mYAccelView.setText(String.valueOf(mAccel[1]));
							mZAccelView.setText(String.valueOf(mAccel[2]));
						}
					} else {
						mXAccelView.setText(String.valueOf(0.0));
						mYAccelView.setText(String.valueOf(0.0));
						mZAccelView.setText(String.valueOf(0.0));
					}

				}
			}
		}

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	// Deemphasize transient forces
	private float lowPass(float current, float gravity) {

		return gravity * mAlpha + current * (1 - mAlpha);

	}

	// Deemphasize constant forces
	private float highPass(float current, float gravity) {
		return Math.abs(current - gravity);
	}

	/**
	 * 报警
	 * 
	 * @param msg
	 *            报警类型消息
	 */
	private void alarm(Message msg) {
		long currenttime = System.currentTimeMillis();
		if (currenttime - lastTime > Constants.ALARM_DIVIDE_MILLIS) {
			if (SharedPrefsUtil.getBooleanValue(instance, "subIsLogin", false)) {
				if (ApplicationUtils.netState(instance)) {
					AlarmType = (String) msg.obj;
					// isAlarming = true;
					int modeCode = getDayOrNight();
					subAlarmPlayVoice(modeCode);
					subAlarmPhotoAndVideo(modeCode);
					lastTime = System.currentTimeMillis();
				} else {
					Show.toast(instance, R.string.internet_exception);
				}
			} else if (currenttime - loginTime > 10000) {
				Show.toast(instance, instance.getString(R.string.please_login));
				loginTime = System.currentTimeMillis();
			}
		}
	}

	/**
	 * 设置闪光灯状态
	 */
	private void setFlashStates() {
		if (1 == getDayOrNight()
				&& subStates.getNightModeStates().isFlashLight()) {
			if (nightMotionOn) {
				nightMotionOn = !nightMotionOn;
			}
			mCameraView.flashModeOn();
			uiHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					nightMotionOn = true;
				}
			}, 2000);
			uiHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					if (null != mCameraView && null != mCameraView.getCamera()) {
						nightMotionOn = false;
						mCameraView.flashModeOff();
					}
				}
			}, Constants.SLEEP_LENGTH);
		}
	}

	/**
	 * 退出操作
	 */
	private void subExit() {
		if (SharedPrefsUtil.getBooleanValue(instance, "subIsLogin", false)) {
			App.netManager.logout(instance, uiHandler);
		} else {
			finish();
		}
		SharedPrefsUtil.putValue(App.mContext, "password", "");
	}

	/**
	 * 结束当前App并返回手机主界面
	 */
	private void sysExit() {
		SharedPrefsUtil.putValue(instance, "subIsLogin", false);
		PubService.isrun = false;
		startActivity(new Intent(instance, AcTiYan.class));
		finish();
		Intent startMain = new Intent(Intent.ACTION_MAIN);
		startMain.addCategory(Intent.CATEGORY_HOME);
		startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(startMain);
		android.os.Process.killProcess(android.os.Process.myPid());
	};

	public static Activity getActivity() {
		return instance;
	}

	private void takeThree() {

		final String folderPath = subUtils.getFileFloderPath(instance);
		if (null != folderPath) {
			String fileName1 = new SimpleDateFormat("yyyyMMddHHmmss")
					.format(new Date()) + "take31" + Constants.PICTURE_SUFFIX;
			takePicture(folderPath, fileName1);
			uiHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					String fileName2 = new SimpleDateFormat("yyyyMMddHHmmss")
							.format(new Date())
							+ "take32"
							+ Constants.PICTURE_SUFFIX;
					takePicture(folderPath, fileName2);
				}
			}, 2000);
			uiHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					String fileName3 = new SimpleDateFormat("yyyyMMddHHmmss")
							.format(new Date())
							+ "take33"
							+ Constants.PICTURE_SUFFIX;
					takePicture(folderPath, fileName3);
				}
			}, 4000);
		} else {
			Show.toast(instance, instance.getString(R.string.check_sdcard));
		}

	}

	private void takeOne() {

		String folderPath = subUtils.getFileFloderPath(instance);
		if (null != folderPath) {
			String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
					.format(new Date()) + "take1" + Constants.PICTURE_SUFFIX;
			takePicture(folderPath, fileName);
		}

	}

	private void recordVideo(int modeCode) {
		Intent intent = new Intent(instance, RecorderActivity.class);
		intent.putExtra(Constants.MODE_CODE, modeCode);
		startActivityForResult(intent, 104);
	}
}
